// subpackagesA/pages/dispatch/dispatch.ts
import {getAllVillage,getAllBuilding,getAllUnit,GetRoomByUnitID,findeRepairPerson,findInfosByHouseID,insertRequestInfo} from '../../../api/room-monitoring'
import dayjs from '../../../utils/day'
Page({

    /**
     * 页面的初始数据
     */
    data: {
      comID:-1,
      userID:-1,
      name:'',
      userName:'',
      userTel:'',
      repairReason:'',
      repairPersonID:'',
      repairPersonName:'',
      roomTemperature:'',
      houseFK:'',
      show:false,
      urgency:false,
      maintain:false,
      time:false,
      timeText:false,
      villageIndex:-1,
      village:'',
      unit:'',
      unitText:'',
      villageID:-1,
      unitID:-1,
      fieldValue:'',
      appointmentTime:'',
      appointmentTimeText:'',
      actions:[
        {
          id:0,
          name:'一般'
        },
        {
          id:1,
          name:'着急'
        },
        {
          id:2,
          name:'紧急'
        }
      ],
      timeList:[
        {
          id:'9:00-12:00',
          name:'9:00-12:00'
        },
        {
          id:'14:00-17:00',
          name:'14:00-17:00'
        }
      ],
      emergencyLeveltext:'',
      emergencyLevel:'',
      maintainList:[
      ],
      options:[
      ],
      // minDate: new Date().getTime(),
      minDate:new Date(dayjs()).getTime(),
      // maxDate: new Date(new Date().getFullYear(),new Date().getMonth()+1).getTime(),
      maxDate:new Date(dayjs().add(10, 'day')).getTime(),
      formatter(type, value) {
        if (type === 'year') {
          return `${value}年`;
        }
        if (type === 'month') {
          return `${value}月`;
        }
        if(type==='day'){
          return `${value}日`
        }
        if(type==='hour' || type==='minute'){
          return ''
        }
        return value;
      },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
      console.log(dayjs().unix())
    },
    onClickLeft(){
      wx.navigateBack({
        delta:1,
      })
    },
    handleModel(){
      wx.navigateTo({
        url:'../newfolder/newfolder'
      })
    },
    onClick(){
      this.setData({
        show:true
      })
    },
    onClose(){
      this.setData({
        show:false,
        urgency:false,
        maintain:false,
        time:false,
        timeText:false
      })
    },
    handleUrgency(){
      this.setData({
        urgency:true
      })
    },
    handleMaintain(){
      this.setData({
        maintain:true
      })
    },
    handleTime(){
      this.setData({
        time:true
      })
    },
    handleTimeText(){
      this.setData({
        timeText:true
      })
    },
    onCascader(e:any){
      const comID = this.data.comID
      console.log(e)
      
      if(e.detail.selectedOptions[0].name=='小区'&&!e.detail.selectedOptions[1]){
        const {text,value,index} = e.detail.selectedOptions[0]
        this.setData({
          villageIndex:index,
          village:text,
        })
        getAllBuilding(comID,value,text).then((res:any)=>{
          console.log(res)
          const list = res.data.data.map((item,e)=>{
            return {
              text:item.buildingName,
              value:item.buildingID,
              index:e,
              name:'楼栋',
              children:[]
            }
          })
          this.updateItem(index,list)
        })
      }else if(e.detail.selectedOptions[1].name=='楼栋'&&!e.detail.selectedOptions[2]){
        const {text,value,index} = e.detail.selectedOptions[1]
        this.setData({
          unitID:index,
          unit:text
        })
        getAllUnit(comID,value,text).then((res:any)=>{
          console.log(res)
          const list = res.data.data.map((item,a)=>{
            return{
              text:item.unitName,
              value:item.unitID,
              index:a,
              name:'单元',
              children:[]
            }
          })
          this.updateItems(this.data.villageIndex,index,list)
        })
      }else if(e.detail.selectedOptions[1].name=='楼栋'&&e.detail.selectedOptions[2]){
        const {text,value,index} = e.detail.selectedOptions[2]
        this.setData({
          unitText:text
        })
        GetRoomByUnitID(value,comID).then((res:any)=>{
          console.log(res)
          const list = res.data.data.map(item=>{
            return{
              text:item.houseName,
              value:item.houseID
            }
          })
          this.updateUnit(this.data.villageIndex,this.data.unitID,index,list)
        })
      }
    },
    updateItem(index:number, newItemValue:any) {
      let updateObj = {};
      let itemKey = `options[${index}].children`; // 构建动态属性字符串
      updateObj[itemKey] = newItemValue; // 使用动态属性名设置更新对象
  
      this.setData(updateObj); // 更新数据
    },
    updateItems(index:number,indexs:number, newItemValue:any) {
      let updateObj = {};
      let itemKey = `options[${index}].children[${indexs}].children`; // 构建动态属性字符串
      updateObj[itemKey] = newItemValue; // 使用动态属性名设置更新对象
  
      this.setData(updateObj); // 更新数据
    },
    updateUnit(index1:number,index2:number,index3:number,newItemValue:any){
      let updateObj = {};
      let itemKey = `options[${index1}].children[${index2}].children[${index3}].children`; // 构建动态属性字符串
      updateObj[itemKey] = newItemValue; // 使用动态属性名设置更新对象
  
      this.setData(updateObj); // 更新数据
    },
    onAll(e:any){
      console.log(e)
      let comID = this.data.comID
      const address = this.data.village + '-' +this.data.unit+'-'+this.data.unitText+'-'+e.detail.selectedOptions[3].text
      this.setData({
        fieldValue:address,
        show:false,
        houseFK:e.detail.selectedOptions[3].value
      })
      findInfosByHouseID(comID,e.detail.selectedOptions[3].value).then(res=>{
        this.setData({
          userName:res.data.holder,
          userTel:res.data.holdPhone
        })
        // console.log(res)
      })
      // console.log(e,this.data.village,this.data.unit,this.data.unitText)
    },
    onUrgency(e:any){
      console.log(e)
      this.setData({
        emergencyLevel:e.detail.id,
        emergencyLeveltext:e.detail.name,
        urgency:false
      })
    },
    onMaintain(e:any){
        console.log(e)
      this.setData({
        repairPersonID:e.detail.id,
        repairPersonName:e.detail.name,
        maintain:false
      })
    },
    onTimeText(e:any){
      this.setData({
        appointmentTimeText:e.detail.name,
        timeText:false
      })
    },
    onTimeValue(e:string){
      const time = dayjs(e.detail)
      const value = dayjs(time.$d).format('YYYY-MM-DD')
      this.setData({
        appointmentTime:value,
        time:false
      })
      console.log(value)
    },
    onInput(e:any){
      this.setData({
        repairReason:e.detail
      })
    },
    onName(e:any){
      this.setData({
        userName:e.detail
      })
    },
    onTel(e:any){
      this.setData({
        userTel:e.detail
      })
    },
    onSubmit(){
      const data = {
        userTel:this.data.userTel,
        userName:this.data.userName,
        repairPersonID:this.data.repairPersonID,
        comID:this.data.comID,
        userID:this.data.userID,
        repairReason:this.data.repairReason,
        repairPerson:this.data.repairPersonName,
        guanjiaName:this.data.name,
        roomTemperature:this.data.roomTemperature,
        appointmentTime:this.data.appointmentTime + ' ' + this.data.appointmentTimeText,
        emergencyLevel:this.data.emergencyLevel,
        houseFk:this.data.houseFK
      }
      const userName = this.data.userName;
      const userTel = this.data.userTel;
      const repairReason = this.data.repairReason
      if(userName==''||userTel==''||repairReason==''){
        wx.showToast({
          icon:'error',
          title:'缺少必填项'
        })
      }else{
        insertRequestInfo(data).then((res:any)=>{
          console.log(res)
          if(res.data==1){
            wx.showToast({
              icon:'success',
              title:'派单成功',
              success:function(){
                wx.navigateBack({
                  delta:2
                })
              }
            })
          }else{
            wx.showToast({
              icon:'error',
              title:'派单失败'
            })
          }
        })
      }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      this.setData({
        comID: wx.getStorageSync("userInfo").data.comID,
        userID:wx.getStorageSync("userInfo").data.userID,
        name:wx.getStorageSync('userInfo').data.name
      })
      let comID = this.data.comID
      let userID = this.data.userID
      getAllVillage(comID).then((res:any)=>{
        console.log(res)
        const list = res.data.data.map((item,index)=>{
          return{
            text:item.villageName,
            value:item.villageID,
            index:index,
            name:'小区',
            children:[]
          }
        })
        this.setData({
          options:list
        })
      })
      findeRepairPerson(userID,comID).then((res:any)=>{
        console.log(res)
        const list = res.data.map(item=>{
          return{
            id:item.id,
            name:item.repairReason
          }
        })
        this.setData({
          maintainList:list
        })
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})